import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/404',
    component: () => import('@/components/NotFound.vue'),
  },
  {
    path: '/:pathMatch(.*)',
    redirect: '/404',
  },
  {
    path: '/login',
    component: () => import('@/views/Login.vue'),
  },
  {
    path: '/',
    component: () => import('@/layout/Layout.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        component: () => import('@/views/Dashboard.vue'),
      },
      {
        path: 'user',
        component: () => import('@/views/user/User.vue'),
      },
      {
        path: 'order',
        component: () => import("@/views/order/Order.vue"),
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

router.beforeEach((to, from) => {
  const isLoggedIn = localStorage.getItem('token')
  if (isLoggedIn && to.path === '/login') {
    return '/'
  }
  if (!isLoggedIn && to.path !== '/login') {
    return '/login'
  }
  return true
})

export default router
